import React, { useState } from 'react';
// 修改导入语句，添加Progress组件
import { Form, Input, Button, Card, message, Typography, Checkbox, Radio, Divider, Alert, Progress } from 'antd';
import { LockOutlined, UserOutlined, MailOutlined, PhoneOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { userService } from '../services/userService';
import type { LoginData, UserType } from '../services/userService';
import '../App.css';

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [authMethod, setAuthMethod] = useState<'email' | 'phone'>('email');
  const [loginMode, setLoginMode] = useState<UserType>('jobseeker'); // 添加登录模式状态
  const [passwordStrength, setPasswordStrength] = useState<'weak' | 'medium' | 'strong'>('weak');
  const [showTwoFactor, setShowTwoFactor] = useState(false);
  const [isAccountLocked, setIsAccountLocked] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  // 密码强度检测
  const checkPasswordStrength = (password: string) => {
    if (!password) {
      setPasswordStrength('weak');
      return;
    }
    
    let strength = 0;
    if (password.length >= 8) strength++;
    if (/[A-Z]/.test(password)) strength++;
    if (/[0-9]/.test(password)) strength++;
    if (/[^A-Za-z0-9]/.test(password)) strength++;
    
    if (strength <= 1) setPasswordStrength('weak');
    else if (strength <= 2) setPasswordStrength('medium');
    else setPasswordStrength('strong');
  };

  const handleLogin = async (values: any) => {
    setLoading(true);
    try {
      // 模拟检测到异常登录
      if (Math.random() > 0.7) {
        setShowTwoFactor(true);
        message.warning('检测到异常登录行为，请进行二次验证');
        setLoading(false);
        return;
      }

      // 模拟账户锁定检测
      if (Math.random() > 0.8) {
        setIsAccountLocked(true);
        message.error('账户因多次登录失败已被暂时锁定');
        setLoading(false);
        return;
      }

      // 准备登录数据
      const loginData: LoginData = {
        email: authMethod === 'email' ? values.emailOrPhone : '',
        password: values.password,
        rememberMe: values.rememberMe || false,
        userType: loginMode // 添加用户类型信息
      };
      
      // 存储登录模式到localStorage
      localStorage.setItem('loginMode', loginMode);

      const response = await userService.login(loginData);
      message.success('登录成功');
      // 保存token和用户信息到localStorage
      localStorage.setItem('token', response.token);
      localStorage.setItem('userInfo', JSON.stringify(response.user));
      navigate('/profile');
    } catch (error) {
      message.error('登录失败，请检查邮箱和密码');
    } finally {
      setLoading(false);
    }
  };

  const handleTwoFactorVerify = () => {
    message.success('验证成功');
    setShowTwoFactor(false);
    // 继续登录流程...
    const values = form.getFieldsValue();
    const loginData: LoginData = {
      email: authMethod === 'email' ? values.emailOrPhone : '',
      password: values.password,
      rememberMe: values.rememberMe || false,
      userType: loginMode // 添加用户类型信息
    };
    
    // 存储登录模式到localStorage
    localStorage.setItem('loginMode', loginMode);
    // 模拟后续登录逻辑
    setTimeout(() => {
      message.success('登录成功');
      navigate('/profile');
    }, 1000);
  };

  const getStrengthColor = () => {
    switch (passwordStrength) {
      case 'weak': return '#f5222d';
      case 'medium': return '#faad14';
      case 'strong': return '#52c41a';
      default: return '#d9d9d9';
    }
  };

  if (isAccountLocked) {
    return (
      <div style={{ 
        minHeight: '100vh', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        padding: '20px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
      }}>
        <Card style={{ width: 400, boxShadow: '0 10px 30px rgba(0,0,0,0.1)' }}>
          <Alert
            message="账户已锁定"
            description="您的账户因多次登录失败已被暂时锁定，请30分钟后再试或联系客服解锁。"
            type="error"
            showIcon
          />
          <Button 
            type="primary" 
            style={{ width: '100%', marginTop: 24 }} 
            onClick={() => navigate('/')}
          >
            返回首页
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      padding: '20px',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Card 
        style={{ 
          width: 400, 
          boxShadow: '0 10px 30px rgba(0,0,0,0.1)',
          borderRadius: '12px',
          overflow: 'hidden'
        }}
      >
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: 8 }}>登录</Title>
          <Text type="secondary">欢迎使用求职管理系统</Text>
        </div>
        
        {/* 登录模式选择 - 只显示求职者和招聘者选项 */}
        <Form.Item>
          <Radio.Group 
            value={loginMode} 
            onChange={(e) => setLoginMode(e.target.value)}
            buttonStyle="solid"
            style={{ width: '100%', marginBottom: 16 }}
          >
            <Radio.Button value="jobseeker">
              求职者登录
            </Radio.Button>
            <Radio.Button value="employer">
              招聘方登录
            </Radio.Button>
          </Radio.Group>
        </Form.Item>
        
        <Form
          form={form}
          name="login"
          layout="vertical"
          onFinish={handleLogin}
        >
          {/* 认证方式选择 */}
          <Form.Item>
            <Radio.Group 
              value={authMethod} 
              onChange={(e) => setAuthMethod(e.target.value)}
              buttonStyle="solid"
              style={{ width: '100%' }}
            >
              <Radio.Button value="email">
                <MailOutlined /> 邮箱登录
              </Radio.Button>
              <Radio.Button value="phone">
                <PhoneOutlined /> 手机登录
              </Radio.Button>
            </Radio.Group>
          </Form.Item>
          
          {/* 邮箱/手机号输入 */}
          <Form.Item
            name="emailOrPhone"
            label={authMethod === 'email' ? "邮箱" : "手机号"}
            rules={[
              { required: true, message: `请输入${authMethod === 'email' ? '邮箱地址' : '手机号'}` },
              authMethod === 'email' 
                ? { type: 'email', message: '请输入有效的邮箱地址' }
                : { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input
              prefix={authMethod === 'email' ? <MailOutlined /> : <PhoneOutlined />}
              placeholder={`请输入${authMethod === 'email' ? '邮箱地址' : '手机号'}`}
              size="large"
            />
          </Form.Item>
          
          {/* 密码输入 */}
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
              size="large"
              visibilityToggle
              onChange={(e) => checkPasswordStrength(e.target.value)}
            />
          </Form.Item>
          
          {/* 密码强度指示器 */}
          <Form.Item style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Progress 
                percent={passwordStrength === 'weak' ? 33 : passwordStrength === 'medium' ? 66 : 100}
                size="small" 
                strokeColor={getStrengthColor()}
                style={{ flex: 1, marginRight: 12 }}
              />
              <Text style={{ color: getStrengthColor() }}>
                {passwordStrength === 'weak' ? '弱' : passwordStrength === 'medium' ? '中' : '强'}
              </Text>
            </div>
          </Form.Item>
          
          {/* 记住我选项 */}
          <Form.Item name="rememberMe" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 16 }}>
            <a href="#" style={{ float: 'right', color: '#1890ff' }}>
              忘记密码?
            </a>
          </Form.Item>
          
          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{ width: '100%', height: 40, fontSize: 16 }}
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
          
          <div style={{ textAlign: 'center', marginTop: 16 }}>
            <Text>
              还没有账号? <a href="/register" style={{ color: '#1890ff' }}>立即注册</a>
            </Text>
          </div>
        </Form>
      </Card>
      
      {/* 二次验证模态框 */}
      {showTwoFactor && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          backgroundColor: 'rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <Card style={{ width: 350 }}>
            <Title level={4}>二次验证</Title>
            <Text>验证码已发送至您的邮箱</Text>
            <Form layout="vertical" style={{ marginTop: 16 }}>
              <Form.Item name="verificationCode" label="验证码" rules={[{ required: true }]}>
                <Input placeholder="请输入验证码" />
              </Form.Item>
              <Form.Item>
                <Button type="primary" style={{ width: '100%' }} onClick={handleTwoFactorVerify}>
                  验证
                </Button>
              </Form.Item>
              <Button type="link" style={{ width: '100%' }} onClick={() => setShowTwoFactor(false)}>
                取消
              </Button>
            </Form>
          </Card>
        </div>
      )}
    </div>
  );
};

export default Login;